import type { BaseAccount } from '@/services/auth'
import { API } from '@/services/common/api'
import type { QywxInfo } from '@/services/qywxs'
import type { ExternalContact } from '../externals'
import type { RawExternalTransfer } from './definition'
import { formatTransferedExternal } from './definition'

/**
 * 获取转交客户列表
 */
export async function getTransfers(accountId: string) {
  return API('/Transfer/List', {
    data: {
      pageSize: 10000,
      pageIndex: 1,
    },
    formatter(raw: RawExternalTransfer[]) {
      return raw.map(item => formatTransferedExternal(item, accountId))
    },
  })
}

/**
 * 转交一个客户
 */
export async function transfer(params: {
  contact: ExternalContact
  qywx: Pick<QywxInfo, 'friendlyName' | 'corpid'>
  fromAccount: Pick<BaseAccount, 'id' | 'name'>
  targetAccount: Pick<BaseAccount, 'id' | 'name'>
  remark: string
}) {
  const { contact, qywx, fromAccount, targetAccount, remark } = params
  return API('/Transfer/Add', {
    data: {
      wxid: contact.ownerWxid,
      wxCompanyName: qywx.friendlyName,
      corpid: qywx.corpid,
      transferWxId: contact.userId,
      transferWxName: contact.name,
      transferWxIcon: contact.avatar,
      fromUserId: fromAccount.id,
      fromUserName: fromAccount.name,
      toUserId: targetAccount.id,
      toUserName: targetAccount.name,
      remark,
    },
  })
}

/**
 * 作为接收方退回客户
 */
export async function transferReturn(id: number) {
  return API(`/transfer/return?id=${id}`)
}

/**
 * 作为发送方收回客户
 */
export async function transferBack(id: number) {
  return API(`/transfer/back?id=${id}`)
}
